<template>
  <div class="main">
    <el-tabs style="width:100%;" @tab-change="tabChange">
      <el-tab-pane label="实时翻译" class="realTimeTranslation">
        <div class="left">
          <el-input type="textarea" :rows="20" v-model="text" placeholder="请输入原文"></el-input>
          <div class="translation-select">
            <span style="font-size:14px">目标语言:</span>
            <el-select v-model="selectedLanguage" placeholder="Select language" style="width:150px;margin-left:10px"
              :popper-class="color === 'night' ?'nightClass':''">
              <el-option v-for="(language, index) in languages" :key="index" :label="language.name"
                :value="language.code"></el-option>
            </el-select>
            <el-button @click="translate" type="primary" style="margin-left:10px">
              翻译
              <el-icon v-if="loading" class="is-loading">
                <Loading />
              </el-icon>
            </el-button>
          </div>
        </div>
        <div class="right">
          <el-input type="textarea" :rows="20" v-model="translatedText"></el-input>
          <el-button class="speakButton" link icon="Tickets" @click="copyAnswer(translatedText)">复制</el-button>
          <el-button class="copyButton" link icon="Headset" @click="speak(translatedText)">朗读</el-button>
        </div>
      </el-tab-pane>
      <el-tab-pane label="历史记录">
        <el-table :data="tableData" stripe style="width: 100%" @cell-click="handleCellClick">
          <el-table-column prop="Name" label="用户" width="180" />
          <el-table-column prop="Model" label="模型" width="180" />
          <el-table-column prop="ChatTitle" label="标题" />
          <el-table-column prop="Question" label="原文" :show-overflow-tooltip="{ popperClass: 'custom-tooltip' }">
            <template #default="{ row }">
              <span class="cell-text">{{ row.Question }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="Answer" label="翻译" :show-overflow-tooltip="{ popperClass: 'custom-tooltip' }">
            <template #default="{ row }">
              <span class="cell-text">{{ row.Answer }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="TransTime" label="时间" >
            <template #default="{ row }">
              <span>{{ parseTime(row.TransTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template #default="scope">
                <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
                <el-button type="success" size="small" @click="handleDetail(scope.row)">详情</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page=pageNum
            :page-size=pageSize background layout="prev, pager, next" :total="total" />
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>

  <historyDialog :resForm="resForm" v-model="historyDialog" @close="close"></historyDialog>

</template>

<script>
import { getgptchat, connrequest } from '../api/connrequest'
import { speakText, parseTime } from '../utils/index'
import historyDialog from './components/historyDialog.vue';

export default {
  name: 'TranslationSelect',
  components: {
    historyDialog
  },
  data() {
    return {
      pageNum: 1,
      pageSize: 10,
      total: 0,
      text: '',
      translatedText: '',
      loading: false,
      selectedLanguage: '英语',
      color:'',
      languages: [
        { name: '英语', code: 'english' },
        { name: '中文', code: 'chinese' },
        { name: '日文', code: 'japanese' },
        { name: '俄语', code: 'russian' },
        // 添加更多语言
      ],
      tableData: [],
      resForm: {
        ChatTitle: '',
        Question: '',
        Answer: ''
      },
      historyDialog: false,
    };
  },
  mounted() {
    this.color = localStorage.getItem("isNightMode") || 'night'
  },
  methods: {
    parseTime,
    copyAnswer(data) {
      let elInput = document.createElement('textarea')
      elInput.value = data
      document.body.appendChild(elInput)
      // 选择对象
      elInput.select()
      // 执行浏览器复制命令
      this.$message.success('复制成功')
      document.execCommand("Copy")
      elInput.remove()
    },
    // 点击单元格复制内容
    handleCellClick(row, column, cell, event) {
      const text = row[column.property];
      if (text) {
        if (navigator.clipboard && navigator.clipboard.writeText) {
          // 现代浏览器使用 Clipboard API
          navigator.clipboard.writeText(text)
            .then(() => {
              this.$message.success('已复制到剪贴板');
            })
            .catch((err) => {
              this.$message.error('复制失败，请手动复制');
              console.error('复制失败:', err);
            });
        } else {
          // 老旧浏览器使用 document.execCommand
          const input = document.createElement('input');
          input.setAttribute('value', text);
          document.body.appendChild(input);
          input.select();
          try {
            document.execCommand('copy');
            this.$message.success('已复制到剪贴板');
          } catch (err) {
            this.$message.error('复制失败，请手动复制');
            console.error('复制失败:', err);
          }
          document.body.removeChild(input);
        }
      }
    },
    async translate() {
      if (!sessionStorage.getItem('Name')) {
        this.loading = false
        this.$message.error('发生错误：请先登录帐号')
        return false
      }
      if (this.text === '' || this.text === undefined) {
        this.$message.info('翻译失败')
        return false
      }
      const text = this.text.trim();
      this.loading = true
      // const API_ENDPOINT = 'https://api.openai.com/v1/chat/completions';
      // const OPENAI_API_KEY = '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'
      try {
        // let prompt = `translate ${text} ${this.selectedLanguage}`
        let prompt = `Translate this into ${this.selectedLanguage}: ${text}`
        this.apiMessage = [
          { role: 'system', content: 'you are a helpful assistant.' },
        ]
        this.apiMessage.push({ role: 'user', content: prompt })
        let model = JSON.parse(sessionStorage.getItem('AiMode')).Translate
        const gptdata = {
          Data: {
            model: model,
            messages: this.apiMessage,
          }
        }
        const response = await getgptchat(gptdata)
        this.loading = false
        const translation = response.Data.choices[0].message.content;
        this.translatedText = translation
        this.WriteChatGPTLog(text, this.translatedText)
        // this.$emit('translation', {translation, binding: this.binding});
      } catch (error) {
        this.loading = false
        this.$message.error('发生错误，请重试！')
      }
    },
    speak() {
      // 获取选中的文本
      const selection = window.getSelection().toString();
      speakText(selection || this.translatedText)
    },
    async tabChange(index) {
      if (index === '1') {
        this.getData()
      }
    },
    async getData() {
      const data = {
        Paging: {
          QueryPageNo: this.pageNum,
          QueryPageLength: this.pageSize
        },
        Filter: {
          Status: 6,
          Name: sessionStorage.getItem('Name')
        }
      }
      const res = await connrequest('GetChatGPTLog', data)
      this.tableData = res.Data
    },
    async WriteChatGPTLog(Question, Answer) {
      let model = (sessionStorage.getItem('RightAI') === '0' || sessionStorage.getItem('RightAI') === '2') ? '3.5' : '4.0'
      const data = {
        Data: {
          Model: '-',
          Action: 6,
          Name: sessionStorage.getItem('Name'),
          Question,
          Answer,
          ChatTitle: Question.substring(0, 20),
        }
      }
      await connrequest('WriteChatGPTLog', data)
    },
    handleSizeChange() { },
    handleCurrentChange(num) {
      this.pageNum = num
      this.getData()
    },
    handleDetail(row) {
      this.resForm.ChatTitle = row.ChatTitle
      this.resForm.Question = row.Question
      this.resForm.Answer = row.Answer
      this.historyDialog = true
    },
    close() {
      this.historyDialog = false
    },
    async handleDelete(row) {
      const data = {
        Data: {
          Id: row.Id
        }
      }
      const res = await connrequest("HideChatGPTLog",data)
      if(res.Status.StatusCode === 0) {
        this.getData()
        this.$message.success("删除成功")
      }

      
    }

  },
};
</script>

<style lang="scss" scoped>
.translation-select {
  position: absolute;
  right: 30px;
  bottom: 30px;
  display: flex;
  align-items: center;
}

.main {
  width: calc(100vw - 100px);

  background: #fff;
  margin: 10px;
  padding: 10px;

  .realTimeTranslation {
    display: flex;
    justify-content: space-between;
    overflow: hidden;

    .left,
    .right {
      position: relative;
      width: 100%;
      height: 430px;
      padding: 20px;
    }

    .copyButton {
      position: absolute;
      bottom: 30px;
      right: 90px;
      z-index: 100;
      color: #409EFF;
    }

    .speakButton {
      position: absolute;
      bottom: 30px;
      right: 30px;
      z-index: 100;
      color: #409EFF;
    }
  }
}



.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
<style scoped>
/* 使用深度选择器穿透 */
:deep(.custom-tooltip) {
  max-width: 800px !important;
  font-size: 14px;
  /* 可选：其他样式 */
}
</style>